<!--
  - Copyright (c) 2019-2025, Goshine All rights reserved.
  - Author: liqifeng (liqifena@gmail.com)
  - Date: 2019-11-13
  - Name:'单位组件'
  - Description: 需要显示默认值则 传入showCascader=false 与:orgData="xxxx"（这个为需要显示的数据） 清空方法为 resetOrgName
                使用selectedChange 方法接收参数 参数形式为{pOrgNo: xxx, orgName: xxx} 树节点选择 方法接收 getSelectedNodes
                showDefault 如果为true 默认显示第一级单位
-->
<template>
  <div class="tree_comp" v-clickoutside="closeTree">
    <Input v-model="treeOrgName" disabled>
      <Button
        slot="append"
        icon="ios-more"
        @click.stop="clickBtn"
        v-if="buttonShowif"></Button>
    </Input>
    <Tree
      :data="treeData"
      class="filter-tree"
      transfer
      @on-select-change="getSelectedNodes"
      v-show="showTree"
    ></Tree>
  </div>
</template>

<script>
import { selAreaTree } from "@/api/sysSetting";
// 自定义指令函数
const clickoutside = {
  bind(el, binding) {
    function handler(e) {
      if (el.contains(e.target) ||( e.target.className && e.target.className.includes(binding.arg))) {
        return false;
      }
      if (binding.expression) {
        binding.value(e);
      }
    }
    el._zClickOutside = handler;
    document.addEventListener("click", handler);
  },
  unbind(el) {
    // 解除事件监听
    document.removeEventListener("click", el._zClickOutside);
    delete el._zClickOutside;
  }
};
export default {
  props: {
    orgData: {
      type: String,
      default: ""
    },
    showDefault: {
      type: Boolean,
      default: false //默认不显示第一级单位
    },
    buttonShowif: {
      type: Boolean,
      default: true
    },
    showName: {
      type: String
    }
  },
  // 注册自定义指令
  directives: { clickoutside },

  data() {
    return {
      treeData: [],
      orgName: [],
      wantedData: {},
      inputData: "",
      showTree: false,
      treeOrgName: ""
    };
  },
  computed: {},
  created() {
    this.getcompanyName();
  },
  mounted() {
  },
  watch: {
    orgName: {
      handler(nVal) {
        if (nVal && nVal.length > 0) {
          this.$emit("selectedChange", this.wantedData);
        } else {
          this.$emit("selectedChange", { pOrgNo: "", orgName: "" });
        }
      },
      deep: true
    },
    orgData: {
      handler(newVal) {
        this.treeOrgName = newVal;
      }
    },
    showName: {
      handler(val){
        if(val){
        this.getcompanyName(val)
        console.log(val,"val")
      }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    clickBtn(){
      this.showTree = !this.showTree
      if(this.showTree && (this.treeData.length > 0 && !this.treeData[0].children)){
        this.treeData = []
        this.getcompanyName()
      }
    },
    //单位名称级联 获取
    getcompanyName(val) {
      console.log(val,'获取单位名称areaNo')
      selAreaTree({areaNo: val}).then(res => {
        if (res.code === 200) {
          var resTree = []
          resTree.push(res.result)
          let arr = [];
          // 递归数据 使之为 label value形式
          resTree.forEach(item => {
            let obj = {};
            item.title = item.attributes.areaTreeVO.areaName;
            item.value = item.attributes.areaTreeVO.areaNo || "";//item.attributes.areaTreeVO.pAreaNo;
            item.label = item.attributes.areaTreeVO.areaName;
            item.orgNo = item.attributes.areaTreeVO.areaNo || ""
            obj = { title: item.title, value: item.value, label: item.label, orgNo: item.orgNo };

            if (item.children && item.children.length > 0) {
              obj.children = [];
              loopList(item.children, obj.children);
            }
            arr.push(obj);
          });
          this.treeData = arr;
          if (this.showDefault && arr.length>0) {
            this.treeOrgName = arr[0].label;
            this.$emit("getSelectedNodes", {
              pOrgNo: arr[0].value || arr[0].orgNo,
              areaName: arr[0].label
            });
            // console.log(arr,"this.areaName")
          }
          function loopList(params, arr) {
            params.forEach(item => {
              let obj = {};
              item.title = item.attributes.areaTreeVO.areaName;
              item.value = item.attributes.areaTreeVO.areaNo || "";//item.attributes.areaTreeVO.pAreaNo;
              item.label = item.attributes.areaTreeVO.areaName;

              obj = { title: item.title, value: item.value, label: item.label };
              if (item.children && item.children.length > 0) {
                obj.children = [];
                loopList(item.children, obj.children);
              }
              arr.push(obj);
            });
          }
        }
      });
    },
    /**
     * 级联change实事件
     */
    handleChange(val, selectedData) {
      let str = "";
      if (selectedData && selectedData.length > 0) {
        str = selectedData[selectedData.length - 1];
        this.wantedData = { pOrgNo: str.value, areaName: str.label };
      }
    },
    /**
     * 树选中节点
     */
    getSelectedNodes(val) {
      console.log(val,"点击树节点")
      if (val && val.length > 0) {
        let str = val[0];
        this.wantedData = { pOrgNo: str.value, areaName: str.label };
        this.treeOrgName = str.label;
        this.showTree = false;
        this.$emit("getSelectedNodes", {
          pOrgNo: str.value,
          areaName: str.label
        });
      }
    },
    /**
     * 点击组件外 关闭树
     */
    closeTree() {
      this.showTree = false;
    },
    /**
     * 清空 v-model的值 在父组件使用this.$refs.xxx.resetOrgName()来清空
     */
    resetOrgName() {
      this.areaName = [];
      this.treeOrgName = "";
      console.log(this.treeOrgName, "this.treeOrgName");
    },
    //转化单位名称的显示格式 只显示最后一级单位
    labelFormat(labels, selectedData) {
      const index = labels.length - 1;
      const data = selectedData[index] || false;
      if (data && data.code) {
        return labels[index] + " - " + data.code;
      }
      return labels[index];
    }
  },
  components: {}
};
</script>

<style scoped lang="scss">
.tree_comp {
  width: 100%;
  position: relative;
}
.filter-tree {
  position: absolute;
  width: 100%;
  border: 1px solid #eee;
  background: #fff;
  z-index: 1000;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: scroll;
}
</style>
